home *** CD-ROM | disk | FTP | other *** search
/ Programming in Microsoft Windows with C# / Programacion en Microsoft Windows con C#.iso / Original Code / Images and Bitmaps / PictureBoxPlusDemo / PictureBoxPlus.cs next >
Encoding:
Text File  |  2001-01-15  |  1.2 KB  |  48 lines

  1. //---------------------------------------------
  2. // PictureBoxPlus.cs ⌐ 2001 by Charles Petzold
  3. //---------------------------------------------
  4. using System;
  5. using System.Drawing;
  6. using System.Windows.Forms;
  7.  
  8. namespace Petzold.ProgrammingWindowsWithCSharp
  9. {
  10.     class PictureBoxPlus: PictureBox
  11.     {
  12.         bool bNoDistort = false;
  13.  
  14.         public bool NoDistort
  15.         {
  16.             get { return bNoDistort; }
  17.             set 
  18.             {
  19.                 bNoDistort = value;
  20.                 Invalidate();
  21.             }
  22.         }    
  23.         protected override void OnPaint(PaintEventArgs pea)
  24.         {
  25.             if ((Image !=  null) && NoDistort &&
  26.                 (SizeMode == PictureBoxSizeMode.StretchImage))
  27.                 ScaleImageIsotropically(pea.Graphics, Image, ClientRectangle);
  28.             else
  29.                 base.OnPaint(pea);
  30.         }
  31.         void ScaleImageIsotropically(Graphics grfx, Image image, Rectangle rect)
  32.         {
  33.             SizeF sizef = new SizeF(image.Width / image.HorizontalResolution,
  34.                                     image.Height / image.VerticalResolution);
  35.  
  36.             float fScale = Math.Min(rect.Width  / sizef.Width,
  37.                                     rect.Height / sizef.Height);
  38.  
  39.             sizef.Width  *= fScale;
  40.             sizef.Height *= fScale;
  41.           
  42.             grfx.DrawImage(image, rect.X + (rect.Width  - sizef.Width ) / 2,
  43.                                   rect.Y + (rect.Height - sizef.Height) / 2,
  44.                                   sizef.Width, sizef.Height);
  45.         }
  46.     }
  47. }
  48.